import cv2 as cv
import numpy as np
import math
import matplotlib.pyplot as plt

'''
读灰度图, 并高斯平滑
'''
img = cv.imread('../pic/rice.png',0)
# img = cv.GaussianBlur(img, (3,3), 1.0)
cv.imshow("gau", img)
##使用局部阈值大津算法
black = cv.adaptiveThreshold(img, 255, cv.ADAPTIVE_THRESH_MEAN_C, cv.THRESH_BINARY, 101, 1)
cv.imshow('ostu', black)
##进一步使用形态学开运算去燥, 可以去掉一些孤立点
ele = cv.getStructuringElement(cv.MORPH_CROSS, (3,3))
dst = cv.morphologyEx(black, cv.MORPH_OPEN, ele)
cv.imshow('black-open:DST', dst)

#检测轮廓
#contours = cv.findContours(dst,cv.RETR_EXTERNAL,cv.CHAIN_APPROX_SIMPLE)
image, contours, hierarchy = cv.findContours(dst,cv.RETR_EXTERNAL,cv.CHAIN_APPROX_SIMPLE)
#绘制轮廓
cv.drawContours(dst, contours, -1, (0,0,255), 1)

riceCnt = 0
riceAll = 0 #米粒总面积
riceArr = [] #米粒面积列表
riceLenArr = []
sigma = 0;
for cnt in contours:
    area = cv.contourArea(cnt)
    if(area < 10):
        continue
    riceCnt += 1
    riceAll += area
    riceArr.append(area)
    #提取矩形坐标
    x,y,w,h = cv.boundingRect(cnt)
    riceLenArr.append( math.sqrt( math.pow(w,2) + math.pow(h,2) ) )
    # print("rice ", riceCnt,"pos: {}-{}".format(x,y),"面积", area)
    cv.rectangle(img, (x,y), (x+w,y+h ), 0x00FF00, 1) #绘制矩形
    cv.putText(img, str(riceCnt),(x,y), cv.FONT_HERSHEY_COMPLEX, 0.4, 0x0000FF, 1)

print("\033[31m米粒总数量：\033[0m", riceCnt)
sigma = np.std(riceArr, ddof=1)
print("米粒平均面积:", round(np.mean(riceArr),2))
print("米粒面积方差:", np.var(riceArr))
print("米粒面积标准差:", np.std(riceArr, ddof=1))

# print(riceArr)
##根据米粒面积统计计算大于3sigma的数量
riceOK = 0
for i in range(0, riceCnt):
    if(riceArr[i] > sigma*3):
        riceOK += 1
print("\033[32m米粒面积大于3sgima数量：", riceOK,"\033[0m")

###根据米粒长度统计
# print(riceLenArr)
sigma = np.std(riceLenArr, ddof=1)
print("米粒平均长度:", np.mean(riceLenArr))
print("米粒长度方差:", np.var(riceLenArr))
print("米粒长度标准差:", sigma)
riceOK = 0
for i in range(0, riceCnt):
    if(riceLenArr[i] > sigma*3):
        riceOK += 1
print("\033[32m米粒长度大于3sgima数量：", riceOK,"\033[0m")

cv.imshow("rice", img)
cv.waitKey()